import { getPayPlatform } from "../../const";
import { util, ParamErr, BaseErr } from "utils";
import { Apps } from "../../config/application";
import type { CommonResult } from "../../types";
import type { Certificate } from "../../utils/Certificate";

/**
 * 创建订单
 * @param cert 证书
 * @param params 参数
 * @param httpInfo 请求信息
 * @returns
 */
async function createOrderAction(
    params: AnyObject,
    httpInfo: AnyObject,
    cert?: Certificate
): Promise<CommonResult> {
    let { platform, orderId, openid } = params || {};
    // 订单id
    if (util.emptyString(orderId)) {
        return [new ParamErr("orderId"), undefined];
    }
    // 用户 openid
    if (util.emptyString(openid)) {
        return [new ParamErr("orderId"), undefined];
    }
    // 支付平台
    let targetPlatform = getPayPlatform(platform);
    if (util.nilValue(targetPlatform)) {
        return [new ParamErr("platform"), undefined];
    }
    // 获取 对应的 配置
    let config = Apps[targetPlatform!];
    if (util.nilValue(config)) {
        return [new BaseErr(-10001, `${targetPlatform}平台 配置错误`), undefined];
    }
    let matchConfig = config!;

    // 创建 预支付订单
    let param = {
        // 应用id
        appid: matchConfig.appId,
        // 商户号
        mchid: matchConfig.mchid,
        // 商品描述
        description: "测试一下",

        out_trade_no: orderId,
        // 订单失效时间
        // time_expire: getNextHourDate(),
        // 附加数据
        attach: `ccdxd`,
        // 回调地址
        notify_url:
            "https://fc-mp-6aab6fa7-d8c7-40bc-b444-bb37fe0f1387.next.bspapp.com/test/wx/pay",
        // 订单金额
        amount: {
            total: 1,
            currency: "CNY",
        },
        payer: {
            openid,
        },
    };

    try {
        const method = "post";
        // 计算签名
        let authSign = getAuth(method.toUpperCase(), API_CreateOrder, param);
        let headers = {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: authSign,
        };

        let fullUrl = API_Base + API_CreateOrder;
        let result = await axios({
            method,
            url: fullUrl,
            data: param,
            headers,
        });
        let { status, data: resData = {}, statusText } = result || {};

        if (status !== 200) {
            console.log("预下单 失败11 ", status, statusText, resData);
            return [new InsideErr(resData), null];
        }
        console.log("预下单 成功 ", resData);
        let { prepay_id = "" } = resData || {};
        return [null, prepay_id];
    } catch (error) {
        let { response = {} } = error || {};
        let { status, statusText, data = {} } = response || {};
        console.log("预下单 失败22  ", status, statusText, data);
        return [new InsideErr(data), null];
    }

    return [undefined, {}];
}

export { createOrderAction };
